import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { useAuthStore } from '@/stores/auth'
import api from '@/api'

export interface WorkOrder {
  id: number
  order_number: string
  title?: string
  status: string
  priority: string
  location?: string
  created_at: string
  creator_name?: string
  assignee_id?: number
  assignee_name?: string
  area_id?: number
  area_name?: string
  custom_fields?: {
    [key: string]: {
      value: any
      field_type: string
      label: string
    }
  }
}

export interface Stats {
  pending: number
  processing: number
  completed: number
}

export function useWorkOrders() {
  const authStore = useAuthStore()
  const loading = ref(false)
  const workOrders = ref<WorkOrder[]>([])
  const stats = ref<Stats>({
    pending: 0,
    processing: 0,
    completed: 0
  })

  // 检查工单是否在用户区域内
  const isOrderInUserArea = (order: WorkOrder, user: any) => {
    if (!order || !user) return false
    
    // 如果工单有area_id，检查是否匹配用户的区域
    if (order.area_id) {
      // 检查用户的主区域
      if (user.area_id === order.area_id) return true
      
      // 检查用户的多区域关联
      if (user.area_ids && Array.isArray(user.area_ids)) {
        return user.area_ids.includes(order.area_id)
      }
    }
    
    // 如果工单有area_name，检查是否匹配用户的区域名称
    if (order.area_name) {
      // 检查用户的主区域名称
      if (user.area_name === order.area_name) return true
      
      // 检查用户的多区域名称
      if (user.areas && Array.isArray(user.areas)) {
        return user.areas.includes(order.area_name)
      }
    }
    
    return false
  }

  // 根据当前标签页过滤工单（简化版，主要依赖后端过滤）
  const getFilteredOrders = (activeTab: string) => {
    if (!workOrders.value || !Array.isArray(workOrders.value)) {
      return []
    }
    
    const currentUser = authStore.user
    if (!currentUser) return []
    
    // 由于后端已经根据角色和区域进行了过滤，这里只需要简单的状态过滤
    return workOrders.value.filter(order => {
      if (activeTab === 'pending') {
        return order.status === 'pending' && !order.assignee_id
      } else if (activeTab === 'processing') {
        return order.status === 'in_progress'
      } else if (activeTab === 'completed') {
        return order.status === 'completed'
      }
      return false
    })
  }

  // 更新统计数据（简化版，主要依赖后端过滤）
  const updateStats = () => {
    if (!workOrders.value || !Array.isArray(workOrders.value)) {
      stats.value = { pending: 0, processing: 0, completed: 0 }
      return
    }
    
    // 由于后端已经根据角色和区域进行了过滤，这里只需要简单的状态统计
    stats.value = {
      pending: workOrders.value.filter(o => 
        o.status === 'pending' && !o.assignee_id
      ).length,
      processing: workOrders.value.filter(o => 
        o.status === 'in_progress'
      ).length,
      completed: workOrders.value.filter(o => 
        o.status === 'completed'
      ).length
    }
  }

  // 加载所有工单数据
  const loadAllWorkOrders = async () => {
    loading.value = true
    try {
      // 同时查询所有状态的工单，启用区域过滤
      const params = {
        per_page: 1000, // 增加每页数量以获取更多数据
        area_filter: true
        // 不指定status参数，获取所有状态的工单
      }
      
      const response = await api.getWorkOrders(params)
      // 确保响应数据结构正确
      workOrders.value = response.data?.work_orders || response.data || []
      updateStats()
    } catch (error) {
      console.error('加载工单失败:', error)
      ElMessage.error('加载工单失败')
      // 确保在错误情况下也有默认值
      workOrders.value = []
    } finally {
      loading.value = false
    }
  }

  // 兼容原有的loadWorkOrders方法，但现在总是加载所有工单
  const loadWorkOrders = async (status?: string) => {
    await loadAllWorkOrders()
  }

  // 接单
  const acceptOrder = async (order: WorkOrder) => {
    try {
      await api.updateWorkOrder(order.id, {
        status: 'in_progress',
        assignee_id: authStore.user?.id,
        actual_start: new Date().toISOString()
      })
      
      ElMessage.success('接单成功')
      // 接单后重新加载所有工单数据以获取最新状态
      await loadAllWorkOrders()
    } catch (error) {
      console.error('接单失败:', error)
      ElMessage.error('接单失败')
      throw error
    }
  }

  return {
    loading,
    workOrders,
    stats,
    loadWorkOrders,
    loadAllWorkOrders,
    getFilteredOrders,
    acceptOrder,
    updateStats
  }
}